# coding:utf-8
from PyQt5.QtWidgets import QWidget,QFileDialog
from PyQt5.QtCore import Qt
from qfluentwidgets import InfoBarPosition, InfoBar
from ui.default_set_ui import Ui_default_set_ui
from src.db_utils import *

class default_set_cls(Ui_default_set_ui,QWidget):
    def __init__(self, parent=None):
        super().__init__()
        # self = Ui_default_set_ui()
        self.setupUi(self)
        self.user_data = []
        self.init_default_area()
        self.select_folder_path = ""
        self.choose_dir.clicked.connect(self.select_folder)
        self.set_data_local.clicked.connect(self.set_data_loc)
        self.add_info.clicked.connect(self.submit_data)

    def set_data_loc(self):
        default_dir = self.select_folder_path
        print("选择的文件夹路径:", default_dir)
        self.config_path = os.path.join('res', 'config', 'config.json')
        with open(self.config_path, 'w') as f:
            json.dump({'folder_path': default_dir}, f)

    def select_folder(self):
        select_folder_path = QFileDialog.getExistingDirectory(self, '选择文件夹')
        if select_folder_path:
            self.choose_dir.setText(select_folder_path)
            self.select_folder_path = select_folder_path

    def init_default_area(self):
        ticket_query ='SELECT DISTINCT province FROM ticket_area'
        db = Database()
        db.fetch_data_and_update_combobox(ticket_query, self.default_area)
        self.default_area.setCurrentText('西藏')
        self.update_service_area()
        self.default_area.currentIndexChanged.connect(self.update_service_area)

    def update_service_area(self):
        selected_item = self.default_area.currentText()
        db = Database()
        c = db.get_connection()
        c.execute("SELECT DISTINCT city FROM ticket_area WHERE province = ?", (selected_item,))
        data_column2 = c.fetchall()
        self.default_city.clear()
        for item in data_column2:
            self.default_city.addItem(item[0])
        self.update_service_area2()
        self.default_city.currentIndexChanged.connect(self.update_service_area2)

    def update_service_area2(self):
        selected_item = self.default_city.currentText()
        db = Database()
        c = db.get_connection()
        c.execute("SELECT district FROM ticket_area WHERE city = ?", (selected_item,))
        data_column3 = c.fetchall()
        self.default_district.clear()
        for item in data_column3:
            self.default_district.addItem(item[0])
        db.close_connection()

    def submit_data(self):
        my_account = self.my_account.text()
        my_passwd = self.my_passwd.text()
        default_name = self.default_name.text()
        default_area = self.default_area.currentText()
        default_time = self.default_time.dateTime().toString("hh:mm:ss")
        default_saller = self.default_saller.currentText()
        default_city = self.default_city.currentText()
        default_district = self.default_district.currentText()

        default_user_check = self.default_user
        default_user_check.setTristate(False)
        default_user = 1 if default_user_check.isChecked() else 0

        if not my_account or not my_passwd or not default_area:
            InfoBar.warning(title='警告',content="请输入工单账号、密码、默认区域！",orient=Qt.Horizontal,isClosable=True,position=InfoBarPosition.TOP_RIGHT,duration=2000,parent=self)
            return

        self.user_data.append((my_account, my_passwd, default_name, default_area, default_time,default_saller,default_city,default_district,default_user))

        self.my_account.clear()
        self.my_passwd.clear()

        try:
            db = Database()
            c = db.get_connection()
            c.execute('''CREATE TABLE IF NOT EXISTS default_set
                         (id INTEGER PRIMARY KEY AUTOINCREMENT, my_account integer, my_passwd integer, default_name integer, default_area integer, default_time DATETIME,default_saller integer,default_city integer,default_district integer,default_user integer)''')
            c.execute("SELECT COUNT(*) FROM default_set")
            total_count = c.fetchone()[0]

            if total_count == 0:
                c.executemany("INSERT INTO default_set (my_account, my_passwd, default_name, default_area, default_time,default_saller,default_city,default_district,default_user) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", self.user_data)
            else:
                c.execute("UPDATE default_set SET my_account = ?, my_passwd = ?, default_name = ?, default_area = ?, default_time = ? ,default_saller = ?,default_city  = ?,default_district  = ?,default_user  = ? WHERE id = ?", (my_account, my_passwd, default_name, default_area, default_time, default_saller,default_city,default_district,default_user, 1))
            db.close_connection()

            InfoBar.success(title='成功',content="默认设置成功！",orient=Qt.Horizontal,isClosable=True,position=InfoBarPosition.TOP_RIGHT,duration=2000,parent=self)
            self.user_data = []
            self.close()

        except sqlite3.Error as e:
            print("An error occurred:", e)
            InfoBar.error(title='错误',content="默认设置失败！",orient=Qt.Horizontal,isClosable=True,position=InfoBarPosition.TOP_RIGHT,duration=2000,parent=self)
